import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:family_app/src/features/gallery/models/photo_model.dart';
import 'package:family_app/src/features/gallery/models/photo_group_model.dart';
import 'package:family_app/src/features/gallery/providers/gallery_provider.dart';
import 'package:family_app/src/features/gallery/providers/photo_group_provider.dart';
import 'package:family_app/src/features/gallery/screens/photo_view_screen.dart';
import 'package:family_app/src/features/gallery/widgets/photo_grid_item.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 相册详情页面
class AlbumDetailScreen extends ConsumerStatefulWidget {
  final String albumId;

  const AlbumDetailScreen({Key? key, required this.albumId}) : super(key: key);
  
  @override
  ConsumerState<AlbumDetailScreen> createState() => _AlbumDetailScreenState();
}

class _AlbumDetailScreenState extends ConsumerState<AlbumDetailScreen> {
  // 是否处于选择模式
  bool _isSelectMode = false;
  // 已选中的照片ID列表
  final Set<String> _selectedPhotoIds = {};

  @override
  Widget build(BuildContext context) {
    final albumAsync = ref.watch(selectedAlbumProvider);
    // 使用新的photoGroupsProvider获取按日期分组的照片列表
    final photoGroupsAsync = ref.watch(photoGroupsProvider(widget.albumId));
    final operationState = ref.watch(albumOperationProvider);

    // 显示操作状态提示
    _showOperationMessage(context, operationState);

    return Scaffold(
      appBar: AppBar(
        title: albumAsync.when(
          data: (album) => Text(album?.name ?? '相册详情'),
          loading: () => const Text('加载中...'),
          error: (_, __) => const Text('相册详情'),
        ),
        actions: [
          // 选择模式下显示取消按钮
          if (_isSelectMode)
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () {
                setState(() {
                  _isSelectMode = false;
                  _selectedPhotoIds.clear();
                });
              },
            )
          else
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: () {
                albumAsync.whenData((album) {
                  if (album != null) {
                    _showEditAlbumDialog(
                        context, ref, album.id, album.name, album.description);
                  }
                });
              },
            ),
        ],
      ),
      body: photoGroupsAsync.when(
        data: (photoGroups) => _buildPhotoGroupList(context, ref, photoGroups),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(
          child: Text('加载失败: $error', style: TextStyle(color: Colors.red)),
        ),
      ),
      // 选择模式下显示底部删除按钮
      bottomNavigationBar: _isSelectMode && _selectedPhotoIds.isNotEmpty
          ? Container(
              color: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 16.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '已选择 ${_selectedPhotoIds.length} 张照片',
                    style: TextStyle(fontSize: 16.sp),
                  ),
                  ElevatedButton.icon(
                    onPressed: () => _showDeleteSelectedPhotosDialog(context),
                    icon: const Icon(Icons.delete),
                    label: const Text('删除'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ],
              ),
            )
          : null,
      floatingActionButton: !_isSelectMode
          ? FloatingActionButton(
              onPressed: () => _showAddPhotoOptions(context, ref),
              backgroundColor: AppTheme.primaryColor,
              child: const Icon(Icons.add_a_photo),
            )
          : null,
    );
  }

  /// 构建照片网格


  /// 构建按日期分组的照片列表
  Widget _buildPhotoGroupList(
      BuildContext context, WidgetRef ref, List<PhotoGroupModel> photoGroups) {
    if (photoGroups.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.photo_outlined, size: 64.r, color: Colors.grey),
            SizedBox(height: 16.h),
            Text(
              '暂无照片',
              style: TextStyle(fontSize: 16.sp, color: Colors.grey),
            ),
            SizedBox(height: 16.h),
            ElevatedButton.icon(
              onPressed: () => _showAddPhotoOptions(context, ref),
              icon: const Icon(Icons.add_a_photo),
              label: const Text('添加照片'),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
              ),
            ),
          ],
        ),
      );
    }

    // 将所有分组中的照片添加到一个列表中，以便在点击照片时查看
    final List<PhotoModel> allPhotos = [];
    for (final group in photoGroups) {
      allPhotos.addAll(group.photos);
    }

    return RefreshIndicator(
      onRefresh: () async {
        ref.invalidate(photoGroupsProvider(widget.albumId));
      },
      child: ListView.builder(
        padding: EdgeInsets.all(8.r),
        itemCount: photoGroups.length,
        itemBuilder: (context, groupIndex) {
          final group = photoGroups[groupIndex];
          final dateStr = _formatDate(group.date);

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 日期标题
              Padding(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Text(
                  dateStr,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: AppTheme.primaryColor,
                  ),
                ),
              ),
              // 照片网格
              GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: MediaQuery.of(context).size.width > 600 ? 4 : 3,
                  crossAxisSpacing: 8.r,
                  mainAxisSpacing: 8.r,
                ),
                itemCount: group.photos.length,
                itemBuilder: (context, photoIndex) {
                  final photo = group.photos[photoIndex];

                  // 计算在所有照片中的索引，以便在点击照片时查看
                  final int globalPhotoIndex = allPhotos.indexWhere((p) => p.id == photo.id);
                  final bool isSelected = _selectedPhotoIds.contains(photo.id);

                  return PhotoGridItem(
                    photo: photo,
                    onTap: () => _isSelectMode
                        ? _togglePhotoSelection(photo.id)
                        : _navigateToPhotoView(context, ref, allPhotos, globalPhotoIndex),
                    onDelete: () => _showDeletePhotoDialog(context, ref, photo),
                    isSelectable: _isSelectMode,
                    isSelected: isSelected,
                    onSelect: () => _togglePhotoSelection(photo.id),
                  );
                },
              ),
              // 每个分组后添加间距
              SizedBox(height: 16.h),
            ],
          );
        },
      ),
    );
  }

  /// 切换照片选择状态
  void _togglePhotoSelection(String photoId) {
    setState(() {
      if (_selectedPhotoIds.contains(photoId)) {
        _selectedPhotoIds.remove(photoId);
      } else {
        _selectedPhotoIds.add(photoId);
      }
      
      // 如果没有选中的照片且处于选择模式，则退出选择模式
      if (_selectedPhotoIds.isEmpty && _isSelectMode) {
        _isSelectMode = false;
      } else if (!_isSelectMode && _selectedPhotoIds.isNotEmpty) {
        // 如果有选中的照片但不处于选择模式，则进入选择模式
        _isSelectMode = true;
      }
    });
  }

  /// 显示删除选中照片的确认对话框
  void _showDeleteSelectedPhotosDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除照片'),
        content: Text('确定要删除选中的 ${_selectedPhotoIds.length} 张照片吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              
              // 逐个删除选中的照片
              for (final photoId in _selectedPhotoIds.toList()) {
                await ref
                    .read(albumOperationProvider.notifier)
                    .deletePhoto(widget.albumId, photoId);
              }
              
              // 清空选中列表并退出选择模式
              setState(() {
                _selectedPhotoIds.clear();
                _isSelectMode = false;
              });
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final dateOnly = DateTime(date.year, date.month, date.day);

    if (dateOnly == today) {
      return '今天';
    } else if (dateOnly == yesterday) {
      return '昨天';
    } else {
      // 使用intl包的DateFormat格式化日期
      final formatter = DateFormat('yyyy年MM月dd日');
      return formatter.format(date);
    }
  }

  /// 显示添加照片选项
  void _showAddPhotoOptions(BuildContext context, WidgetRef ref) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(16.r))),
      builder: (context) => SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading:
                    const Icon(Icons.camera_alt, color: AppTheme.primaryColor),
                title: const Text('拍照'),
                onTap: () async {
                  Navigator.pop(context);
                  await ref
                      .read(albumOperationProvider.notifier)
                      .takePhotoAndAddToAlbum(widget.albumId);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library,
                    color: AppTheme.primaryColor),
                title: const Text('从相册选择'),
                onTap: () async {
                  Navigator.pop(context);
                  await ref
                      .read(albumOperationProvider.notifier)
                      .pickImagesAndAddToAlbum(widget.albumId);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示编辑相册对话框
  void _showEditAlbumDialog(BuildContext context, WidgetRef ref, String albumId,
      String name, String? description) {
    final nameController = TextEditingController(text: name);
    final descriptionController = TextEditingController(text: description);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('编辑相册'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(labelText: '相册名称'),
              autofocus: true,
            ),
            SizedBox(height: 8.h),
            TextField(
              controller: descriptionController,
              decoration: const InputDecoration(labelText: '相册描述（可选）'),
              maxLines: 2,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final newName = nameController.text.trim();
              final newDescription = descriptionController.text.trim();
              if (newName.isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('相册名称不能为空')),
                );
                return;
              }
              Navigator.of(context).pop();
              await ref.read(albumOperationProvider.notifier).updateAlbum(
                    albumId,
                    name: newName,
                    description:
                        newDescription.isNotEmpty ? newDescription : null,
                  );
            },
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }

  /// 显示删除照片确认对话框
  void _showDeletePhotoDialog(
      BuildContext context, WidgetRef ref, PhotoModel photo) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除照片'),
        content: const Text('确定要删除这张照片吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              await ref
                  .read(albumOperationProvider.notifier)
                  .deletePhoto(widget.albumId, photo.id);
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 导航到照片查看页面
  void _navigateToPhotoView(BuildContext context, WidgetRef ref,
      List<PhotoModel> photos, int initialIndex) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => PhotoViewScreen(
          photos: photos,
          initialIndex: initialIndex,
          albumId: widget.albumId,
        ),
      ),
    );
  }

  /// 显示操作状态提示
  void _showOperationMessage(BuildContext context, AlbumOperationState state) {
    if (state.isSuccess && state.message != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(state.message!)),
        );
      });
    } else if (!state.isSuccess && state.error != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(state.error!),
            backgroundColor: Colors.red,
          ),
        );
      });
    }
  }
}
